package com.project.tools;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.project.config.GiteeImgBed;
import com.project.config.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class GiteeUploadTools {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public  String uploadImg(MultipartFile file) throws Exception {
        logger.info("请求成功");
        String originaFileName = file.getOriginalFilename();
        //上传图片不存在时
        if(originaFileName == null){
            return null;
        }

        String suffix = originaFileName.substring(originaFileName.lastIndexOf("."));
        //设置图片名字
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + suffix;

        String paramImgFile = Base64.encode(file.getBytes());
        //设置转存到Gitee仓库参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", GiteeImgBed.ACCESS_TOKEN);
        paramMap.put("message", GiteeImgBed.ADD_MESSAGE);
        paramMap.put("content", paramImgFile);

        //转存文件路径
        String targetDir = GiteeImgBed.PATH + fileName;
        //设置请求路径
        String requestUrl = String.format(GiteeImgBed.CREATE_REPOS_URL, GiteeImgBed.OWNER,
                GiteeImgBed.REPO_NAME, targetDir);
        //logger.info("请求Gitee仓库路径:{}",requestUrl);
        logger.info("https://gitee.com/Delicate_gray/bai/raw/master"+targetDir);



        String resultJson = HttpUtil.post(requestUrl, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        //表示操作失败
        if (jsonObject==null || jsonObject.getObj("commit") == null) {
            return null;
        }
        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));
        //存放的url
        return content.getObj("download_url").toString();
    }
}
